package com.czh.config;

import com.czh.constant.CommonConstant;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 死信交换机和延迟队列处理消息
 *
 * @author chenzhihua
 * @Date 2024/7/29
 */
@Configuration
public class LazyQueueAndDeadExchangeConfig {
    // 定义延迟队列
    @Bean
    public Queue delayedQueue() {
        return QueueBuilder.durable(CommonConstant.DELAYED_QUEUE)
                .withArgument("x-dead-letter-exchange", "dlx_exchange")
                .withArgument("x-dead-letter-routing-key", "dlx_routing_key")
                .build();
    }

    // 定义死信交换机
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange("dlx_exchange");
    }

    // 定义死信队列
    @Bean
    public Queue dlq() {
        return QueueBuilder.durable(CommonConstant.DLQ).build();
    }

    // 绑定延迟队列和原始交换机
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(delayedQueue())
                .to(new DirectExchange(CommonConstant.EXCHANGE_NAME))
                .with(CommonConstant.LAZY_ROUTE_KEY);
    }

    // 绑定死信队列和死信交换机
    @Bean
    public Binding dlqBinding() {
        return BindingBuilder.bind(dlq())
                .to(dlxExchange())
                .with("dlx_routing_key");
    }
}
